﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.EntityModel;

namespace MonkeyWarranty.Web.Errors
{
    public partial class New : System.Web.UI.Page
    {
        #region Properties

        private ErrorBiz _errorBiz;
        private ErrorBiz ErrorManager
        {
            get { return _errorBiz ?? (_errorBiz = new ErrorBiz()); }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // get auto code
                var nextCode = ErrorManager.GetNextCode();
                txtCode.Text = string.Format("{0:00000}", nextCode);
                txtSortOrder.Text = nextCode.ToString(CultureInfo.InvariantCulture);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            lblErrorMessage.Text = string.Empty;
            errorMessage.Visible = false;
            // validate inputs
            var code = txtCode.Text.Trim();
            if (code.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.CodeIsRequired;
                errorMessage.Visible = true;
                return;
            }
            var name = txtName.Text.Trim();
            if (name.Length == 0)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.NameIsRequired;
                errorMessage.Visible = true;
                return;
            }
            var descrition = txtDescription.Text;
            int sortOrder;
            int.TryParse(txtSortOrder.Text.Trim(), out sortOrder);
            var isHidden = chkHidden.Checked;

            var error = new Error
            {
                Code = code,
                Name = name,
                Description = descrition,
                SortOrder = sortOrder,
                Hidden = isHidden
            };

            error = ErrorManager.CreateError(error);

            if (error == null)
            {
                lblErrorMessage.Text = Resources.GlobalStrings.CreateFailed;
                errorMessage.Visible = true;
                return;
            }

            // success
            Response.Redirect("List.aspx");
        }

        #endregion
    }
}